<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where">
          <a-row>
            <a-form-item label="牧云汇平台ID:">
              <a-input v-model:value.trim="where.hzaxxId" placeholder="请输入牧云汇平台ID" allow-clear />
            </a-form-item>           
            <a-form-item label="状态:">
              <a-select
                show-search
                v-model:value="where.onlineStatus"
                style="width: 120px"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                allow-clear
              >
                <a-select-option value='1'>在线</a-select-option>
                <a-select-option value='2'>离线</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="所属牧场:" name="ranchId">
              <a-select
                show-search
                v-model:value="where.ranchId"
                placeholder="请选择所属牧场"
                style="width: 205px;"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                @change="selectRanch"
                allow-clear
                @clear="clearRanchRelated"
              >
                <a-select-option v-for="item in ranchList" :key="item.ranchId" >
                  {{ item.ranchName }}
                </a-select-option>
              </a-select>
            </a-form-item>


            <a-form-item label="所属牛舍:" name="oxtId">
              <a-select
                show-search
                v-model:value="where.oxtId"
                placeholder="请选择所属牛舍"
                style="width: 200px"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                @change="selectOxtall"
                allow-clear
                @clear="clearOxtallRelated"
              >
                <a-select-option v-for="item in oxtallList" :key="item.oxtallId" >
                  {{ item.oxtallName }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="所属区域:" name="areaId">
              <a-select
                show-search
                v-model:value="where.areaId"
                placeholder="请选择所属区域"
                style="width: 200px"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                allow-clear
              >
                <a-select-option v-for="item in areaList" :key="item.areaId" >
                  {{ item.areaName }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item class="ele-text-center">
              <a-space>
                <a-button type="primary" @click="reload">查询</a-button>
                <a-button @click="reset">重置</a-button>
              </a-space>
            </a-form-item>

          </a-row>
        </a-form>
      </a-card>
    </div>
    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="groupId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          :scroll="{ x: 'max-content' }"
        >
      
          <!-- table操作栏按钮 -->
          <template #bodyCell="{ column, record }">

            <!-- 牛舍字段可编辑 -->
            <template v-if="column.dataIndex === 'oxtallName'">
              <div v-if="editingId === record.cameraId && editingField === 'oxtallName'">
                <div style="display: flex; flex-direction: column;">
                  <a-select
                    v-model:value="editingOxtallId"
                    style="width: 120px; margin-bottom: 4px;"
                    placeholder="请选择牛舍"
                  >
                    <a-select-option v-for="item in tempOxtallList" :key="item.oxtallId">
                      {{ item.oxtallName }}
                    </a-select-option>
                  </a-select>
                  <div style="display: flex; justify-content: center;">
                    <a-button type="link" size="small" @click="saveOxtall(record)" style="padding: 0 8px;">
                      <check-outlined />
                    </a-button>
                    <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                      <close-outlined />
                    </a-button>
                  </div>
                </div>
              </div>
              <div v-else>
                <a-space>
                  <span>{{ record.oxtallName }}</span>
                  <a-button type="link" size="small" @click="startEditOxtall(record)">
                    <edit-outlined />
                  </a-button>
                </a-space>
              </div>
            </template>
            
            <!-- 区域字段可编辑 -->
            <template v-if="column.dataIndex === 'areaName'">
              <div v-if="editingId === record.cameraId && editingField === 'areaName'">
                <div style="display: flex; flex-direction: column;">
                  <a-select
                    v-model:value="editingAreaId"
                    style="width: 120px; margin-bottom: 4px;"
                    placeholder="请选择区域"
                  >
                    <a-select-option v-for="item in tempAreaList" :key="item.areaId">
                      {{ item.areaName }}
                    </a-select-option>
                  </a-select>
                  <div style="display: flex; justify-content: center;">
                    <a-button type="link" size="small" @click="saveArea(record)" style="padding: 0 8px;">
                      <check-outlined />
                    </a-button>
                    <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                      <close-outlined />
                    </a-button>
                  </div>
                </div>
              </div>
              <div v-else>
                <a-space>
                  <span>{{ record.areaName }}</span>
                  <a-button type="link" size="small" @click="startEditArea(record)">
                    <edit-outlined />
                  </a-button>
                </a-space>
              </div>
            </template>

            <!-- 其他列的模板 -->
            <template v-if="column.key === 'onlineStatusColumn'">
              <a-tag v-if="record.onlineStatus == 1" color="green">在线</a-tag>
              <a-tag v-else color="red">离线</a-tag>
            </template>

            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openManager(record)">管理</a>
                <a-divider type="vertical" />
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
    <!-- 编辑弹窗 -->
     <DeviceManagerdeviceAiedgeComputerCameraManagerModal v-if="showCameraManagerModal" v-model:visible="showCameraManagerModal" :data="current" @done="reload"  />
  </div>
</template>

<script>
import { PlusOutlined } from '@ant-design/icons-vue';
import { RanchApi } from '@/api/property/RanchApi';
import { OxtallApi } from '@/api/property/OxtallApi';
import { AreaApi } from '@/api/property/AreaApi';
import { message } from 'ant-design-vue';
import { EditOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { DeviceAiEdgeCameraApi } from '@/api/property/aiedgecomputer/DeviceAiEdgeCameraApi';
import DeviceManagerdeviceAiedgeComputerCameraManagerModal from './camera-manager-modal.vue'
export default {
  name: 'DeviceManagerdeviceAiedgeComputerCameraList',
  components: {
    PlusOutlined,
    EditOutlined,
    CheckOutlined,
    CloseOutlined,
    DeviceManagerdeviceAiedgeComputerCameraManagerModal
  },
  async mounted() {
  },
  async created() {
    let that = this;
    RanchApi.list({}).then(resp => {
      let _ranchList = (resp ? resp.data : null) || [];
      this.ranchList = _ranchList;
      if (_ranchList.length > 0) {
        OxtallApi.list({"orgId" : _ranchList[0].ranchId}).then(result => {
          this.oxtallList = (result ? result.data : null) || [];
          if (this.oxtallList.length > 0) {
            AreaApi.list({"oxtId" : this.oxtallList[0].oxtallId}).then(result => {
              that.areaList = (result? result.data : null) || [];
            }).catch((err) => {
              console.log(err)
            });
          }
        }).catch((err) => {
          console.log(err)
        });
      }
    });
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '相机ID',
          dataIndex: 'cameraId',
          width: 80
        },
        {
          title: '牧云汇平台ID',
          dataIndex: 'hzaxxId',
          width: 80
        },
        {
          title: '设备名称',
          dataIndex: 'name',
          width: 100
        },
        {
          title: '牧场',
          dataIndex: 'ranchName',
          width: 120
        },
        {
          title: '牛舍',
          dataIndex: 'oxtallName',
          width: 120
        },
        {
          title: '区域',
          dataIndex: 'areaName',
          width: 120
        },
        {
          title: '排序',
          dataIndex: 'orderNum',
          width: 20,
        },
        {
          title: '在线状态',
          key: 'onlineStatusColumn',
          dataIndex: 'onlineStatus',
          width: 70,
        },
        {
          title: '状态更新时间',
          dataIndex: 'onlineStatusTime',
          width: 120,
        },
        {
          title: 'ip',
          dataIndex: 'cameraIp',
          customRender: function(row) {
            let str = "";
            if (row.record.cameraIp) {
              str = row.record.cameraIp;
            }
            if (row.record.port) {
              str += ":" + row.record.port;
            }
            return str;
          },
          width: 120,
        },
        {
          title: '操作',
          key: 'action',
          width: 80,
          align: 'center',
          fixed: 'right',
        }
      ],
      // 表格搜索条件
      where: {},
      // 当前编辑数据
      current: null,
      ranchList : [],
      oxtallList : [],
      areaList : [],
      showCameraModal : false,
      editingId: null,
      editingValue: null,
      // 添加新的编辑状态变量
      editingField: null,
      editingOxtallId: null,
      editingAreaId: null,
      // 临时存储编辑时的选项列表
      tempOxtallList: [],
      tempAreaList: [],
      showCameraManagerModal : false
    };
  },
  methods: {
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2025/03/08 10:06
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    reloadCurrent(){
      const page = this.$refs.table.tablePagination.current || 1;
      this.$refs.table.reload({ page: page });
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2025/03/08 10:06
     */
    reset() {
      this.where.hzaxxId = '';
      this.where.onlineStatus = undefined;
      this.where.oxtId = undefined;
      this.where.ranchId = undefined;
      this.where.areaId = undefined;
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2025/03/08 10:06
     */
    openManager(row) {
      this.current = row;
      this.showCameraModal = true;
    },
    /**
     * 获取表格数据
     *
     * @author fengshuonan
     * @date 2022/5/8 15:18
     */
    datasource({ page, limit, where, orders }) {
      return DeviceAiEdgeCameraApi.findFullPage({ ...where, ...orders, pageNo: page, pageSize: limit });
    },

    selectRanch(ranchId) {
      this.oxtallList = [];
      this.areaList = [];
      this.where.queryAreaId = undefined;
      this.where.queryOxtallId = undefined;
      let that = this;
      OxtallApi.list({"orgId" : ranchId}).then(result => {
        this.oxtallList = (result ? result.data : null) || [];
        if (this.oxtallList.length > 0) {
          AreaApi.list({"oxtId" : this.oxtallList[0].oxtallId}).then(result => {
            that.areaList = (result? result.data : null) || [];
          }).catch((err) => {
            console.log(err)
          });
        }
      }).catch((err) => {
        console.log(err)
      });
    },

    selectOxtall(oxtId) {
      this.areaList = [];
      this.where.queryAreaId = undefined;
      let that = this;
      AreaApi.list({"oxtId" : oxtId}).then(result => {
        that.areaList = (result? result.data : null) || [];
      }).catch((err) => {
        console.log(err)
      });
    },


    clearRanchRelated() {
      // 清空牛舍选择
      this.where.oxtId = undefined;
      // 清空区域选择
      this.where.areaId = undefined;
      // 清空相关列表数据
      this.oxtallList = [];
      this.areaList = [];
    },
    clearOxtallRelated() {
      // 清空区域选择
      this.where.areaId = undefined;
      this.areaList = [];
    },


    
    /**
     * 取消编辑
     */
     cancelEdit() {
      this.editingId = null;
      this.editingValue = null;
      this.editingField = null;
      this.editingOxtallId = null;
      this.editingAreaId = null;
    },

    
    /**
     * 开始编辑牛舍
     */
    async startEditOxtall(record) {
      if (!record.ranchId) {
        message.warning('请先设置[AI边缘计算机设备]牧场');
        return;
      }
      
      this.editingId = record.cameraId;
      this.editingField = 'oxtallName';
      this.editingOxtallId = record.oxtallId == '0'? undefined : record.oxtallId;
      
      // 获取牛舍列表，基于当前记录的牧场ID
      try {
        const result = await OxtallApi.list({"orgId": record.ranchId});
        this.tempOxtallList = (result ? result.data : null) || [];
        if (this.tempOxtallList.length === 0) {
          message.warning('当前牧场下没有牛舍');
        }
      } catch (err) {
        console.log(err);
        message.error('获取牛舍列表失败' + (err.message || '未知错误'));
      }
    },

    /**
     * 保存牛舍
     */
    async saveOxtall(record) {
      try {
        const updateData = {
          cameraId: record.cameraId,
          oxtId: this.editingOxtallId,
          // 清空区域和牛栏信息
          areaId: 0,
        };
        
        await DeviceAiEdgeCameraApi.editAreaInfo(updateData);
        message.success('牛舍更新成功');
        
        // 更新当前记录的牛舍信息
        const selectedOxtall = this.tempOxtallList.find(item => item.oxtallId === this.editingOxtallId);
        if (selectedOxtall) {
          record.oxtallId = selectedOxtall.oxtallId;
          record.oxtallName = selectedOxtall.oxtallName;
          // 清空区域和牛栏信息，因为牛舍变了
          record.areaId = null;
          record.areaName = '';
        }
        
        this.cancelEdit();
      } catch (error) {
        message.error('牛舍更新失败' + (error.message || '未知错误'));
      }
    },

    /**
     * 开始编辑区域
     */
    async startEditArea(record) {
      if (!record.oxtallId) {
        message.warning('请先设置牛舍');
        return;
      }
      
      this.editingId = record.cameraId;
      this.editingField = 'areaName';
      this.editingAreaId = record.areaId == '0'? undefined : record.areaId;
      
      // 获取区域列表，基于当前记录的牛舍ID
      try {
        const result = await AreaApi.list({"oxtId": record.oxtallId});
        this.tempAreaList = (result ? result.data : null) || [];
        if (this.tempAreaList.length === 0) {
          message.warning('当前牛舍下没有区域');
        }
      } catch (err) {
        console.log(err);
        message.error('获取区域列表失败' + (err.message || '未知错误'));
      }
    },

    /**
     * 保存区域
     */
    async saveArea(record) {
      try {
        const updateData = {
          cameraId: record.cameraId,
          areaId: this.editingAreaId
        };
        
        await DeviceAiEdgeCameraApi.editAreaInfo(updateData);
        message.success('区域更新成功');
        
        // 更新当前记录的区域信息
        const selectedArea = this.tempAreaList.find(item => item.areaId === this.editingAreaId);
        if (selectedArea) {
          record.areaId = selectedArea.areaId;
          record.areaName = selectedArea.areaName;
        }
        
        this.cancelEdit();
      } catch (error) {
        message.error('区域更新失败' + (error.message || '未知错误'));
      }
    },
    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2025/03/08 10:06
     */
    openManager(row) {
      this.current = row;
      this.showCameraManagerModal = true;
    },



  }
};
</script>
